package core
{
	import flash.events.Event;
	import flash.utils.getDefinitionByName;
	import flash.utils.setTimeout;
	
	import org.ais.system.Ais;
	import org.ais.system.Memory;
	import org.aisy.display.USprite;
	import org.aisy.net.data.FileTemp;

	public class WinClose extends USprite
	{
		public function WinClose()
		{
		}
		
		public function connect(im:*):void
		{
			im = null;
			try {
				Ais.IMain.stage.nativeWindow;
			}
			catch (error:*) {
				Ais.IMain.Swf.remove(Ais.IMain.Swf.hasSwf("swf", parent));
				return;
			}
			__addEvent();
			im = null;
		}
		
		private function __addEvent():void
		{
			Ais.IMain.stage.nativeWindow.addEventListener("close", __nativeWindowHandler);
		}
		
		private function __removeEvent():void
		{
			Ais.IMain.stage.nativeWindow.removeEventListener("close", __nativeWindowHandler);
		}
		
		private function __nativeWindowHandler(e:*):void
		{
			var app:* = getDefinitionByName("flash.desktop.NativeApplication").nativeApplication;
			if (app.openedWindows.length <= 1) {
				if (app.openedWindows.length === 1 && /iSunday/.test(app.openedWindows[0].stage.getChildAt(0).toString()) === true) {
					FileTemp.clear();
				}
				app.dispatchEvent(new Event("exiting"));
				app.exit();
			}
			else {
				__removeEvent();
				Ais.IMain.clear();
				setTimeout(__clear, 1000 * 5);
			}
			app = null;
			e = null;
		}
		
		private function __clear():void
		{
			Memory.clear(1);
		}
		
	}
}